<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.searchKey" :placeholder="$t('table.search')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in searchOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>
      <el-input :placeholder="$t('adfiles.title')" v-model="listQuery.searchValue" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.is_available" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in availableOptions" :key="index" :label="item.label" :value="item.value"/>
      </el-select>
      <el-select v-model="listQuery.positions"  class="filter-item" :placeholder="$t('adfiles.position')" >
          <el-option v-for="item in positionList" :key="item.id" :label="item.name" :value="item.id"/>
      </el-select>
      <el-date-picker
                        v-model="listQuery.start_at"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.start_date_from')"
                        :end-placeholder="$t('placeholder.start_date_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
      <el-date-picker
                        v-model="listQuery.end_at"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.expiry_date_from')"
                        :end-placeholder="$t('placeholder.expiry_date_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
    </div>
    <div class="filter-container">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
    </div>
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      :default-sort = "{prop: 'id', order: 'descending'}"
      @sort-change="adsListSort"
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column
        :label="$t('table.id')"
        align="center"
        width="65" sortable="custom" prop="id">
        <template slot-scope="scope" >
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('table.area')"
        align="center"
        width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.area_name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('table.available')"
        align="center"
        width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.available_name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('adfiles.title')"
        align="center"
        prop="image"
        min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('adfiles.position')"
        align="center"
        width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.position_name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('adfiles.image')"
        align="center"
        width="200">
        <template slot-scope="scope">
          <img :src="(scope.row.image.indexOf('http')>=0?scope.row.image:scope.row.imageDomain+scope.row.image)" style="width: 80px;height: 80px">
        </template>
      </el-table-column>

      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('adfiles.link')"
        align="center"
        width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.link }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('adfiles.start_at')"
        align="center"
        width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.start_at }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('adfiles.end_at')"
        align="center"
        width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.end_at }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.sort')" width="160px" align="center" sortable="custom" prop="sort">
        <template slot-scope="scope">
          <span><el-input v-model="scope.row.sort" type="number" min="0" @change="handelAdsSort(scope.row)" /></span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230">
        <template slot-scope="scope">
          <el-button type="primary" size="small" class="el-icon-edit" @click="handleUpdate(scope.row.id)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="small" class="el-icon-delete" @click="destroyRecord(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="indexRecord" />

    <detail ref="detail" :is-edit="isEdit" :edit-id="editId" @indexRecord="indexRecord"/>

  </div>
</template>

<script>
import adApi from '@/api/ad/ad'
import positionApi from '@/api/ad/position'
import Detail from './components/Detail'

import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import i18n from '@/lang/index'

export default {
  name: 'Tag',
  components: { Pagination, Detail },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      ad_ids: [],
      positionList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        positions: [],
        start_at: [],
        end_at: [],
        area: this.$store.getters.area,
        lang: i18n.locale,
        page: 1,
        limit: 20,
        is_available: 2,
        title: '',
        sort: 'desc',
        orderby: 'id',
        searchKey: 'title',
        searchValue: ''
      },
      availableOptions: [
        { 'label': i18n.t('table_element.available.all'), 'value': 2 },
        { 'label': i18n.t('table_element.available.on'), 'value': 1 },
        { 'label': i18n.t('table_element.available.un'), 'value': 0 }
      ],
      editId: 0,
      isEdit: false,
      searchOptions: [
        { value: 'title', label: i18n.t('adfiles.title') }
      ]
    }
  },
  created() {
    this.indexRecord()
    this.fetchAllPosition()
  },
  methods: {

    handleFilter() {
      this.listQuery.page = 1
      this.indexRecord()
    },

    handleCreate() {
      this.$refs.detail.handShowDetailDialog(0)
    },

    handleUpdate(id) {
      this.$refs.detail.handShowDetailDialog(id)
    },

    indexRecord() {
      this.listLoading = true
      adApi.indexRecord(this.listQuery).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.list = serviceResponse.data.data
          this.total = serviceResponse.data.total
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    destroyRecord(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        adApi.destroyRecord(row.id).then(response => {
          const serviceResponse = response.data
          if (serviceResponse.code === 0) {
            this.$message({
              type: 'success',
              message: 'success!'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          } else {
            this.$message({
              type: 'error',
              message: 'error!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Canceled deletion'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        adApi.mulDestroyRecord({ ad_id: this.ad_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success',
              type: 'success',
              duration: 2000
            })
            this.indexRecord()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.ad_ids.indexOf(element.id) == -1) {
          this.ad_ids.push(element.id)
        }
      })
    },
    adsListSort(params) {
      // console.log(params.order)
      this.listQuery.orderby = params.prop
      this.listQuery.sort = params.order == 'ascending' ? 'asc' : 'desc'
      this.indexRecord()
    },
    handelAdsSort(row) {
      adApi.fetchSort(row.id, event.target.value).then((res) => {
        if (res.data.code == 0) {
          this.positionList = res.data.data
        }
      })
    },

    fetchAllPosition() {
      positionApi.showAll({}).then((res) => {
        if (res.data.code == 0) {
          this.positionList = res.data.data
        }
      })
    },
    resetForm() {
      this.$refs.postForm.clearValidate()
    }
  }
}
</script>
